// const AV = require('../../../utils/av-weapp.js')
const pageInterceptor = require('../../../components/pageInterceptor').pageInterceptor;
const api = require('../../../api/api');
const request = require('../../../components/request');
const util = require('../../../utils/util');

// Page({
pageInterceptor({
  data: {
    /**
     * 商品和其对应的图片列表
     */
    goodsAndImageUrlList: {},
    current: 0,
    galleryHeight: getApp().screenWidth
  },
  onLoad: function (options) {
    var goodsId = options.objectId;
    // 根据商品id，加载商品及其对应的图片
    this.getGoodsById(goodsId);
  },
  /**
   * 根据商品id，加载商品及其对应的图片
   * @param {*} goodsId 
   */
  getGoodsById: function (goodsId) {
    let that = this;
    var url = util.restfulFormat(api.data.prefix + api.data.url.goods.findGoodsAndImageUrlListByGoodsId, {goodsId: goodsId});
    request.get(url, null, {
      'content-type': 'application/json',
    }).action((res) => {
      console.log(`接口${api.data.url.goods.findGoodsAndImageUrlListByGoodsId}：${JSON.stringify(res)}`);
      that.setData({
        goodsAndImageUrlList: res.data.result
      });
    }).catch(err => {
      console.error(err);
    });
  },
  /**
   * 点击“加入购物车”按钮
   */
  addCart: function () {
    this.insertCart(this.data.goodsAndImageUrlList);
  },
  /**
   * 商品加入购物车
   */
  insertCart: function (goodsAndImageUrlList) {
    let that = this;
    request.post(api.data.prefix + api.data.url.addCart, {
      userId: wx.getStorageSync('userInfo').userId,
      goodsId: goodsAndImageUrlList.goods.id,
      quantity: 1
    }, {
      'content-type': 'application/json',
    }).action((res) => {
      console.log(`接口${api.data.url.addCart}：${JSON.stringify(res)}`);
      that.showCartToast();
    }).catch(err => {
      console.error(err);
    });
  },
  /**
   * 展示提示框
   */
  showCartToast: function () {
    wx.showToast({
      title: '已加入购物车',
      icon: 'success',
      duration: 1000
    });
  },
  /**
   * 全屏预览图片
   * @param {*} e 
   */
  previewImage: function (e) {
    let urlArray = [];
    this.data.goodsAndImageUrlList.imageUrlList.forEach((item, index) => {
      urlArray.push(item);
    });
    wx.previewImage({
      //从<image>的data-current取到current，得到String类型的url路径
      current: urlArray[parseInt(e.currentTarget.dataset.current)],
      urls: urlArray // 需要预览的图片http链接列表
    })
  },
  /**
   * 跳转到购物车页面
   */
  showCart: function () {
    wx.switchTab({
      url: '../../cart/cart'
    });
  }
  // })
}, true)